﻿using ExcellentProjectPlus.Aplicacion.Cuestionarios;
using ExcellentProjectPlus.Aplicacion.Cuestionarios.Recursos;
using ExcellentProjectPlus.Dominio.Cuestionarios.Entidades;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Description;
using Servicios.Cuestionarios.Models;
using System.Configuration;

namespace Servicios.Cuestionarios.Controllers
{
    public class RecursosController : ApiController
    {
        #region Propiedades
        IServicioDeGestionDeRecursos _servicioDeGestionDeRecursos;
        #endregion

        #region Constructores
        public RecursosController(IServicioDeGestionDeRecursos servicioDeGestionDeRecursos)
        {
            _servicioDeGestionDeRecursos = servicioDeGestionDeRecursos;
        }
        #endregion

        //POST SUBIR RECURSOS
        [Route("api/uploadfile")]

        public async Task<HttpResponseMessage> PostFormData()
        {

            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var root = ConfigurationManager.AppSettings["DirPath"]; // HttpContext.Current.Server.MapPath("~/App_Data");

            if (string.IsNullOrWhiteSpace(root))
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Path not defined");

            var provider = new MultipartFormDataStreamProvider(root);

            try
            {
                await Request.Content.ReadAsMultipartAsync(provider);
                //data
                var fileInfo = new Servicios.Cuestionarios.Models.FileInfo()
                {
                    name = provider.FileData[0]
                    .LocalFileName.Replace(root, string.Empty).Replace("\"", string.Empty),
                    size = "100",
                    url = ""
                };
                var infos = new FileInfos();
                infos.files = new List<Servicios.Cuestionarios.Models.FileInfo>();
                infos.files.Add(fileInfo);

                return Request.CreateResponse(HttpStatusCode.OK, infos);
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }
        //GET
        [HttpGet]
        [ResponseType(typeof(Recurso))]
        public IHttpActionResult ObtenerTodos()
        {
            IEnumerable<Recurso> recursos = _servicioDeGestionDeRecursos.ObtenerRecursos();
            if (recursos == null)
            {
                return NotFound();
            }

            return Ok(recursos);
        }

        //GET
        [HttpGet]
        [Route("api/recursos/{id}")]
        [ResponseType(typeof(Recurso))]
        public IHttpActionResult ObtenerRecursoPorId(int id)
        {
            Recurso recurso = _servicioDeGestionDeRecursos.ObtenerRecursoPorId(id);
            if (recurso == null)
            {
                return NotFound();
            }

            return Ok(recurso);
        }

        [HttpPost]
        [ResponseType (typeof(Recurso))]
        public IHttpActionResult PostRecurso(Recurso recurso)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            _servicioDeGestionDeRecursos.AgregarRecurso(recurso);

            return CreatedAtRoute("DefaultApi", new { id = recurso.IdRecurso }, recurso);
        }

        [HttpPut]
        [Route("api/recursos/{id}")]
        [ResponseType (typeof(Recurso))]
        public IHttpActionResult PutRecurso(int id, [FromBody]Recurso recurso)
        {
            if (!ModelState.IsValid)
                return BadRequest(ModelState);

            if (id != recurso.IdRecurso)
                return BadRequest();

            _servicioDeGestionDeRecursos.ModificarRecurso(recurso);

            return StatusCode(HttpStatusCode.NoContent);

        }

        [HttpDelete]
        [Route("api/recursos/{id}")]
        [ResponseType (typeof(Recurso))]
        public IHttpActionResult DeleteRecurso(int id)
        {
            Recurso recurso = _servicioDeGestionDeRecursos.ObtenerRecursoPorId(id);

            if(recurso == null)            
                return NotFound();

            _servicioDeGestionDeRecursos.EliminarRecurso(recurso);
            return Ok(recurso);
        }

    }
}